package cn.yuanqiao.archive.supervision.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantRyMjDzb;
import cn.yuanqiao.archive.appManager.service.impl.TenantMijiComparisonTableServiceImpl;
import cn.yuanqiao.archive.supervision.domain.YqIssuedNotice;
import cn.yuanqiao.archive.supervision.mapper.AddAnnualInspectionMaterialsMapper;
import cn.yuanqiao.archive.supervision.service.AddAnnualInspectionMaterialsService;
import cn.yuanqiao.archive.xiaoxitongzhi.domain.YqXxtz;
import cn.yuanqiao.archive.xiaoxitongzhi.mapper.YqXxtzMapper;
import cn.yuanqiao.archive.xiaoxitongzhi.service.IYqXxtzService;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : 庸人一个
 * @create : 2024/3/13 15:29
 */
@Slf4j
@Service
public class AddAnnualInspectionMaterialsServiceImpl implements AddAnnualInspectionMaterialsService {

    @Resource(name = "addAnnualInspectionMaterialsMapper")
    private AddAnnualInspectionMaterialsMapper mapper;

    @Autowired
    private YqXxtzMapper yqXxtzMapper;

    @Value("${FBswitch}")
    private Boolean FBswitch;
    @Autowired
    private TenantMijiComparisonTableServiceImpl mijiComparisonTableService;

    @Autowired
    IYqXxtzService yqXxtzService;

    @Override
    public List<YqIssuedNotice> findPage(YqIssuedNotice issuedNotice) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("dagly")) {
            List<YqIssuedNotice> page = new ArrayList<>();
            if (issuedNotice.getMaterialState()==1) {
                issuedNotice.setTenantCode(SecurityUtils.getTenantCode());
                page = mapper.findPage(issuedNotice);
            }
            if(issuedNotice.getMaterialState() == 2){
                page = mapper.findPage(issuedNotice);
            }
            return page;
        }
        return null;
    }

    @Override
    public AjaxResult updateStatus(Long id, String type) {
        if ("2".equals(type)) {
            YqIssuedNotice issuedNotice = mapper.findById(id);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate parse = LocalDate.parse(issuedNotice.getDeadline(), formatter);
            LocalDate now = LocalDate.parse(LocalDate.now().format(formatter));
            if (parse.isBefore(now)) {
                mapper.updateStatus(id, type);
                return AjaxResult.success("修改状态成功");
            }
        } else {
            mapper.updateStatus(id, type);
            return AjaxResult.success("修改状态成功");
        }
        return AjaxResult.error("已过期，无法修改状态");
    }

    @Override
    public YqIssuedNotice findNotice(Long id) {
        YqIssuedNotice issuedNotice = mapper.findNotice(id);
        String mjWhere = "";
        if(FBswitch){
            List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
            mjWhere=(" and a.MJ in ('" + getdamjbyrymj.stream().map(m->m.getDaMj()).collect(Collectors.joining("','")) +"') ");
        }
        issuedNotice.setAttachmentsList(mapper.findByAttachments(issuedNotice,mjWhere));
        return issuedNotice;
    }

    @Override
    public void remind(String tenantCode) {
        try {
            if (StringUtils.isNotEmpty(tenantCode)) {
                List<Long> userIds = mapper.findByUserId(tenantCode);
                if (CollectionUtils.isNotEmpty(userIds)) {
                    userIds.forEach(item -> {
                        YqXxtz yqXxtz = initYqXxtz(tenantCode, item);
                        yqXxtzService.insertYqXxtzAndYqXxfbfw(yqXxtz);
                      //  yqXxtzMapper.addYqXxtz(yqXxtz);
                       // yqXxtzMapper.addYqXxfbfw(yqXxtz);
                    });
                }
            }
        }catch (Exception e){
            log.error("提醒失败",e);
            throw new RuntimeException("提醒失败");
        }

    }

    @Override
    public AjaxResult updateById(YqIssuedNotice issuedNotice) {
        issuedNotice.setUpdateTime(new Date());
        issuedNotice.setUpdateUser(SecurityUtils.getUsername());
        if ("2".equals(issuedNotice.getState())) {
            YqIssuedNotice byId = mapper.findById(issuedNotice.getId());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate parse = LocalDate.parse(byId.getDeadline(), formatter);
            LocalDate now = LocalDate.parse(LocalDate.now().format(formatter));
            if (now.isBefore(parse)||now.isEqual(parse)) {
                mapper.updateById(issuedNotice);
                return AjaxResult.success("修改状态成功");
            }else {
                return AjaxResult.error("已过截至时间，无法提交自检");
            }
        } else {
            mapper.updateById(issuedNotice);
            return AjaxResult.success("修改状态成功");
        }
    }

    @Override
    public Map statistics() {
        return mapper.statistics();
    }


    /**
     * 初始化消息
     *
     * @param tenantCode 企业编码
     * @param item 用户id
     * @return YqXxtz
     */
    private YqXxtz initYqXxtz(String tenantCode, Long item) {
        YqXxtz yqXxtz = new YqXxtz(tenantCode);
        long id = SnowflakeIdGenerator.generateId();
        yqXxtz.setId(id);
        yqXxtz.setMsg("年检材料上报提醒,请注意查收");
        yqXxtz.setType(4);
        yqXxtz.setIsRead(0);
        yqXxtz.setRecipientsId(item);
        yqXxtz.setPublisherId(SecurityUtils.getUserId());
        yqXxtz.setCreateTime(DateUtils.getNowDate());
        return yqXxtz;
    }

}
